package com.xjun.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.xjun.pojo.User;
import com.xjun.utils.JsonUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

//@Controller
@RestController //类下面的全部方法都不走视图解析器,返回Json
//@RequestMapping("/json")
public class UserController {
    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {
        //创建一个Jackson的对象映射器，用来解析数据
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        User user = new User("潇君", 3, "男");
        //将对象解析成为Json格式
        String string = mapper.writeValueAsString(user);
        return string;
    }

    @RequestMapping("/j2")
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<User> users = new ArrayList<>();
        User user1 = new User("潇君一号", 3, "男");
        User user2 = new User("潇君二号", 3, "男");
        User user3 = new User("潇君三号", 3, "男");
        User user4 = new User("潇君四号", 3, "男");
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        return mapper.writeValueAsString(users);
    }

    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //不使用时间戳的方式
        mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
        //自定义日期格式对象
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //指定日期格式
        mapper.setDateFormat(simpleDateFormat);
        Date date = new Date();
        return mapper.writeValueAsString(date);
    }

    //=====================================
    //开始使用自建工具类JsonUtils中的getJson
    //=====================================
    @RequestMapping("/j4")
    public String json4() {
        User user = new User("自建工具类JsonUtils中的getJson潇君", 6, "男");
        return JsonUtils.getJson(user);
    }

    @RequestMapping("/j5")
    public String json5() {
        ArrayList<User> users = new ArrayList<>();
        User user1 = new User("自建工具类JsonUtils中的getJson潇君一号", 6, "男");
        User user2 = new User("自建工具类JsonUtils中的getJson潇君二号", 6, "男");
        User user3 = new User("自建工具类JsonUtils中的getJson潇君三号", 6, "男");
        User user4 = new User("自建工具类JsonUtils中的getJson潇君四号", 6, "男");
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        return JsonUtils.getJson(users);
    }

    @RequestMapping("j6")
    public String json6() {
        Date date = new Date();
        return JsonUtils.getJson(date);
    }
}
